package com.sunchen.asc.auth.rest;

import com.nimbusds.jose.jwk.JWKSet;
import com.sunchen.asc.auth.component.LoginUserHolder;
import com.sunchen.asc.auth.dto.OauthTokenDto;
import com.sunchen.asc.auth.service.UserDetailService;
import com.sunchen.asc.service.common.ResultResponse;
import com.sunchen.asc.service.user.dto.UserDto;
import com.sunchen.asc.service.common.ResultUtil;
import com.sunchen.asc.service.user.vo.NewUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import com.nimbusds.jose.jwk.RSAKey;
import springfox.documentation.annotations.ApiIgnore;

import java.security.KeyPair;
import java.security.Principal;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

@Api("管理端用户鉴权")
@RestController
@RequestMapping("/oauth/")
public class AuthRest {

    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private KeyPair keyPair;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private LoginUserHolder loginUserHolder;

    /**
     * Oauth2登录认证
     */
    @ApiOperation("创建用户")
    @RequestMapping(value = "/user/create", method = RequestMethod.POST)
    public ResultResponse createUser(NewUserVo userVo){
        return userDetailService.createUser(userVo);
    }

    @ApiOperation("获取令牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name="grant_type",value = "获取方式",dataType = "String",required = true,defaultValue = "password"),
            @ApiImplicitParam(name="client_id",value = "终端类型id",dataType = "String"),
            @ApiImplicitParam(name="client_secret",value = "终端验证密码",dataType = "String"),
            @ApiImplicitParam(name="username",value = "用户登录名",dataType = "String"),
            @ApiImplicitParam(name="password",value = "用户登录密码",dataType = "String")
    })
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ResultResponse<OauthTokenDto> postAccessToken(@ApiIgnore Principal principal, @ApiIgnore @RequestParam Map<String, String> parameters){
        OAuth2AccessToken oAuth2AccessToken = null;
        try {
            oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        } catch (HttpRequestMethodNotSupportedException e) {
            e.printStackTrace();
        }
        OauthTokenDto oauth2TokenDto = OauthTokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();
        return ResultUtil.success(oauth2TokenDto);
    }

    @ApiOperation("令牌接口")
    @GetMapping("/rsa/publicKey")
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
    @GetMapping("/current/user")
    public UserDto currentUser() {
        return loginUserHolder.getCurrentUser();
    }


}
